from django.shortcuts import render,redirect
from django.http import JsonResponse
from sm_system.views import COOKIE_NAME
from sm_system.models import *
from tools import id_generate
import logging
logging.basicConfig(level=logging.INFO)
from django.http import HttpResponse
# Create your views here.


# 分部功能
def index(request):

    clerks = ClerkInfo.objects.all()
    context = {"clerks": clerks}
    return render(request, 'clerk/clerk.html', context)


# 职员编号生成
def clerk_id(request):

    flag = True
    while flag:
        temp_id = id_generate(how_many=1, length=4)[0]
        try:
            ClerkInfo.objects.get(id=temp_id)
        except Exception as e:
            logging.info(e)
            only_id = temp_id
            flag = False
    context = {'clerk_id': str(only_id)}
    return JsonResponse(context)


def update(request, id):

    clerk = ClerkInfo.objects.get(id=id)
    context = {"clerk": clerk}
    return render(request, 'clerk/clerkUpdate.html', context)


def update_form(request):

    if request.POST:
        id = request.POST['id']
        clerk = ClerkInfo.objects.get(id=id)
        clerk.supermarket_id = request.POST['supermarket_id']
        clerk.name = request.POST['name']
        clerk.contact = request.POST['contact']
        clerk.dept_id = request.POST['dept_id']
        clerk.save()

    return redirect('/clerk/index/')


def add(request):

    return render(request, 'clerk/clerkAdd.html')


def add_form(request):
    if request.POST:
        clerk = ClerkInfo()
        clerk.id = request.POST['id']
        clerk.supermarket_id = request.POST['supermarket_id']
        clerk.name = request.POST['name']
        clerk.dept_id = request.POST['dept_id']
        clerk.contact = request.POST['contact']
        clerk.save()

    return redirect('/clerk/index/')


def delete(request, id):

    clerk = ClerkInfo.objects.get(id=id)
    clerk.delete()
    return redirect('/clerk/index/')

